
cc.Class({
    extends: cc.Component,

    init(config) {
        this.plotInfo = config.dialogs
        this.touchLayer = this.node.getChildByName('touchLayer')

        this.isLoadingDialog = false
        this.showingIndex = 0
        // console.log(this.plotInfo, 'info')
        this.showNext(this.showingIndex)
        this.touchLayer.on(cc.Node.EventType.TOUCH_START, this.handleTouch, this)
    },

    changeAvatar(url) {
        const imgNode = this.node.getChildByName('avatar')
        cc.loader.loadRes(url, cc.SpriteFrame, (err, res) => {
            if (err) {
                return console.error('图片加载失败 plotWindow.js', err)
            }

            const size = imgNode.width
            const originSize = imgNode.getComponent(cc.Sprite).spriteFrame.getOriginalSize()
            const ratio = originSize.width / originSize.height

            imgNode.getComponent(cc.Sprite).spriteFrame = res

            if (ratio > 1) {
                imgNode.width = size
                imgNode.height = size / ratio
            } else {
                imgNode.height = size
                imgNode.width = size * ratio
            }
        })
    },

    changeDialog(message) {
        this.isLoadingDialog = true

        let msgIndex = 0
        const label = this.node.getChildByName('dialog').getChildByName('descLabel').getComponent(cc.Label)
        const oneByShowMsg = () => {
            msgIndex++
            label.string = message.slice(0, msgIndex)

            if (msgIndex >= message.length) {
                this.isLoadingDialog = false
                this.unschedule(oneByShowMsg)
            }
        }

        this.schedule(oneByShowMsg, 0.1)
    },

    changeName(name) {
        const label = this.node.getChildByName('nameLabel').getComponent(cc.Label)
        label.string = name
    },

    showNext(index) {
        const config = this.plotInfo[index]

        this.changeAvatar(config.person.avatar)
        this.changeDialog(config.dialog)
        this.changeName(config.person.name)
    },

    handleTouch() {
        if (this.isLoadingDialog) {
            return
        }

        this.showingIndex++

        if (this.showingIndex > this.plotInfo.length - 1) {
            this.close()
        } else {
            this.showNext(this.showingIndex)
        }

    },

    close() {
        this.node.destroy()
    }

    // update (dt) {},
});
